<style scoped>
.img-face {
    max-width: 200px;
    max-height: 200px;
    padding: 10px;
    cursor: pointer;
}
</style>
<template>
    <div>
        <Form class="form-more" ref="formValidate" :model="tempData" :label-width="80" :rules="ruleValidate">
            <Row :gutter="5">
                <Col span="6">
                    <FormItem label="就诊日期" prop="OrderDate">
                        <DatePicker :clearable="false" type="date" format="yyyy年MM月dd日" :readonly="isReadOnly" v-model="tempData.OrderDate"></DatePicker>
                    </FormItem>
                </Col>
                <Col span="4">
                    <FormItem label="年龄">
                        <InputNumber v-model="tempData.CustomerAge" :readonly="isReadOnly" :precision="precision" :min="1" placeholder="年龄" />
                    </FormItem>
                </Col>
                <Col span="6">
                    <FormItem label="医保号" prop="CustomerId">
                        <Input v-model="tempData.CustomerId" style="display:none"></Input>
                        <Input v-model="tempData.medicalCardNo" readonly>
                            <Icon type="ios-more" size="32" v-if="!isReadOnly" style="cursor: pointer" slot="suffix" @click="choseCustomer()" />
                        </Input>
                    </FormItem>
                </Col>
                <Col span="6" v-if="!isReadOnly">
                    <Button type="primary" @click="choseProduct()" icon="md-add">选择药品</Button>
                </Col>
                <Col span="6" v-if="isReadOnly">
                    <Button type="primary" @click="GetSaleOrderAndPrint(Id)" icon="md-print">打印</Button>
                </Col>
            </Row>
            <vxe-table style="margin-bottom: 10px" border ref="xTable" resizable show-overflow height="400px" align="center" :edit-rules="validRules" :data="tempDetail" :footer-method="footerMethod" :edit-config="!isReadOnly ? {
                    trigger: 'click',
                    mode: 'row',
                    showIcon: false,
                    autoClear: false,
                } : null">
                <vxe-column type="seq" width="60" title="序号"></vxe-column>
                <vxe-column field="ProductName" title="药品"></vxe-column>
                <vxe-column field="Num" width="150" title="数量" :edit-render="{}">
                    <template #edit="{ row }">
                        <vxe-input v-model="row.Num" type="integer" min="1" @change="updateFooterEvent"></vxe-input>
                    </template>
                </vxe-column>
                <vxe-column field="Unit" width="100" title="单位"></vxe-column>
                <vxe-column field="Price" width="150" title="单价(元)" :edit-render="{}">
                    <template #edit="{ row }">
                        <vxe-input v-model="row.Price" type="number" @change="updateFooterEvent"></vxe-input>
                    </template>
                </vxe-column>
                <vxe-column field="Amount" width="150" title="金额(元)" :edit-render="{}">
                    <template #edit="{ row }">
                        <span>{{ countAmount(row) }}</span>
                    </template>
                </vxe-column>
                <vxe-column field="Product.Num" width="150" title="库存"></vxe-column>
                <vxe-column field="Remark" title="备注" :edit-render="{}">
                    <template #edit="{ row }">
                        <vxe-input v-model="row.Remark" type="text"></vxe-input>
                    </template>
                </vxe-column>
                <vxe-column title="操作" width="80" v-if="!isReadOnly">
                    <template #default="{ seq }">
                        <Button size="small" type="error" @click="removeRowEvent(seq)">删除</Button>
                    </template>
                </vxe-column>
            </vxe-table>
            <Row>
                <Col span="5">
                    <FormItem label="金额" prop="AllFee">
                        <Input v-model="AllFee" readonly type="number">
                            <span slot="append">元</span>
                        </Input>
                    </FormItem>
                </Col>
            </Row>
            <FormItem label="症状" prop="Symptom">
                <Input v-model="tempData.Symptom" :readonly="isReadOnly" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }" />
            </FormItem>
            <FormItem label="临床诊断" prop="Remark">
                <Input v-model="tempData.Remark" :readonly="isReadOnly" type="textarea" :autosize="{ minRows: 5, maxRows: 5 }" />
            </FormItem>
            <!-- <FormItem label="备注" prop="Remark">
        <Input v-model="tempData.Remark" :readonly="isReadOnly" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }" />
            </FormItem>-->
            <!-- <FormItem v-if="!isReadOnly" label="是否打印" prop="Remark">
        <RadioGroup size="large" v-model="isPrint">
          <Radio :label="0">否</Radio>
          <Radio :label="1">是</Radio>
        </RadioGroup>
            </FormItem>-->
        </Form>
        <div class="div-footer" v-if="!isReadOnly" :size="customSize">
            <Button type="text" @click="cancel()">取消</Button>
            <Button type="info" :loading="loading" @click="SaveSaleOrder(0)">暂存</Button>&nbsp;&nbsp;
            <Button type="success" :loading="loading" @click="SaveSaleOrder(2)">提交</Button>
        </div>
        <Modal :footer-hide="true" :width="1000" draggable v-model="modalCustomer" title="选择人员" :mask-closable="false">
            <customerchose v-if="modalCustomer" @on-success="getCustomer" />
        </Modal>
        <Modal :footer-hide="true" :width="1000" draggable v-model="modalProduct" title="选择药品" :mask-closable="false">
            <productchose v-if="modalProduct" @on-success="getProduct" />
        </Modal>
        <iframe id="iframe-print" frameborder="0" style="display: none" scrolling="auto" :src="printSrc"></iframe>
    </div>
</template>

<script>
import {
    SearchProduct,
    GetSaleOrder,
    GetSaleOrderAndPrint,
    SaveSaleOrder
} from '@/api/saleorder'
import customerchose from '../customer/customerchose.vue'
import productchose from '../product/productchose.vue'
import { GetSystemConfig } from '@/api/data'
export default {
    name: 'saleorder',
    props: ['Id', 'Type'],
    components: {
        customerchose, productchose
    },
    data() {
        const validatePass = ({ cellValue, rule, row, column }) => {
            if (cellValue < 1) {
                return new Error('数量必须大于0')
            }
            if (cellValue > row.Product.Num) {
                return new Error('数量不能大于库存')
            }
        }
        return {
            Extras: {},
            printSrc: '/static/print/saleorder.html?temp=' + Date.parse(new Date()),
            tableHeight: 450,
            customSize: 8,
            loading: false,
            tempData: {
                displayName: ''
            },
            isPrint: 0,
            modalTemp: false,
            tempDetail: [],
            precision: 0,
            validRules: {
                Price: [
                    { required: true, message: '价格不能为空', trigger: 'manual' },
                    { type: 'number', min: 0.0001, message: '大于0', trigger: 'manual' }
                ],
                Num: [
                    { required: true, message: '数量不能为空', trigger: 'manual' },
                    //{ type: 'integer', min: 1, message: '大于0', trigger: 'manual' },
                    { validator: validatePass }
                ],
            },
            modalCustomer: false,
            modalProduct: false,
            configData: {},
            dataProduct: [],
            ruleValidate: {

            }

        }
    },
    computed: {
        isReadOnly() {
            return this.Type == 1
        },
        AllFee() {
            let vm = this
            var amount = 0
            if (vm.configData.config4 == 1) {
                this.tempDetail.forEach((item) => {
                    if (item.Price && item.Num) {
                        amount += Math.floor(Number(item.Price) * Number(item.Num))
                    }
                })
                if (this.tempData.FreightFee) {
                    amount += Number(this.tempData.FreightFee)
                }

                if (this.tempData.GiveupFee) {
                    amount -= Number(this.tempData.GiveupFee)
                }
                return Math.floor(amount)
            } else {
                this.tempDetail.forEach((item) => {
                    if (item.Price && item.Num) {
                        amount += Number(item.Price) * Number(item.Num)
                    }
                })
                if (this.tempData.FreightFee) {
                    amount += Number(this.tempData.FreightFee)
                }
                if (this.tempData.GiveupFee) {
                    amount -= Number(this.tempData.GiveupFee)
                }
                return amount.toFixed(2)
            }
        }
    },

    methods: {
        cancel() {
            this.$emit('on-success', 0)
        },
        handleSearch(value) {
            if (!value.trim()) {
                return
            }
            let vm = this
            var reqData = {
                page: 1,
                size: 15,
                keyword: value
            }
            SearchProduct(reqData).then((res) => {
                var data = res.data
                if (data.StatusCode == 200) {
                    vm.dataProduct = data.Data.Items.map((x) => x.Name)
                }
            })
        },
        countAmount(row) {
            let vm = this
            if (row.Price && row.Num) {
                if (vm.configData.config4 == 1) {
                    row.Amount = Math.floor(row.Price * row.Num)
                } else {
                    row.Amount = row.Price * row.Num
                }
            } else {
                row.Amount = 0
            }

            return row.Amount
        },

        removeRowEvent(seq) {
            var index = seq - 1
            console.log(index)
            this.tempDetail.splice(index, 1)
        },

        updateFooterEvent() {
            setTimeout(() => {
                const $table = this.$refs.xTable
                $table.updateFooter()
            }, 100)
        },
        footerMethod({ columns, data }) {
            return [
                columns.map((column, columnIndex) => {
                    if (columnIndex === 0) {
                        return '合计'
                    }
                    if (['Num', 'Amount'].includes(column.property)) {
                        return this.sumNum(data, column.property)
                    }
                    return null
                })
            ]
        },
        sumNum(list, field) {
            let count = 0
            list.forEach((item) => {
                count += Number(item[field])
            })
            return count
        },
        choseCustomer() {
            this.modalCustomer = true
        },
        getCustomer(data) {
            let vm = this
            vm.modalCustomer = false
            vm.tempData.displayName = data.DisplayName
            vm.tempData.CustomerName = data.Name
            vm.tempData.CustomerId = data.Id
            vm.tempData.medicalCardNo = data.MedicalCardNo
            console.log(vm.tempData.CustomerId)
        },
        choseProduct() {
            this.modalProduct = true
        },
        getProduct(data) {
            let vm = this
            vm.modalProduct = false
            var choseArr = []
            data.forEach(e => {
                var has = false
                vm.tempDetail.forEach(s => {
                    if (e.Id == s.ProductId) {
                        has = true
                    }
                })
                if (!has) {
                    choseArr.push({
                        ProductId: e.Id,
                        ProductName: e.Name,
                        ProductCode: e.Code,
                        Unit: e.Unit,
                        Specification: e.Specification,
                        Num: 1,
                        Price: e.Price,
                        Amount: e.Price,
                        Product: {
                            Num: e.Num
                        },
                        Remark: ''
                    })
                }
            })

            vm.tempDetail = vm.tempDetail.concat(choseArr)
        },
        async SaveSaleOrder(status) {
            debugger
            let vm = this
            const $table = this.$refs.xTable
            const errMap = await $table.validate(true).catch((errMap) => errMap)
            if (errMap) {
                console.log('验证失败')
                return
            }

            if (typeof vm.tempData.OrderDate === 'object') {
                vm.tempData.OrderDate = vm
                    .dayjs(vm.tempData.OrderDate)
                    .format('YYYY年MM月DD日')
            }
            if (!vm.tempData.OrderDate) {
                this.$Message.warning('日期不能为空')
                return
            }
            if (!vm.tempData.CustomerId) {
                this.$Message.warning('人员不能为空')
                return
            }
            if (vm.tempDetail.length <= 0) {
                this.$Message.warning('请添加药品')
                return
            }
            vm.tempData.FreightFee = Number(vm.tempData.FreightFee)
            vm.tempData.GiveupFee = Number(vm.tempData.GiveupFee)
            vm.tempData.PayFee = Number(vm.tempData.PayFee)
            var reqData = {
                order: vm.tempData,
                detail: vm.tempDetail,
                status: status
            }
            vm.loading = true
            SaveSaleOrder(reqData).then((res) => {
                vm.loading = false
                const data = res.data
                if (data.StatusCode == 200) {
                    vm.modalTemp = false
                    vm.$Message.success({ title: '提示', content: '保存成功' })
                    if (vm.isPrint) {
                        vm.GetSaleOrderAndPrint(data.Data)
                    }
                    vm.$emit('on-success', 1)
                } else {
                    vm.$Message.error({ title: '提示', content: data.Errors })
                }
            })
        },
        GetSaleOrder() {
            let vm = this
            GetSaleOrder(this.Id).then((res) => {
                debugger;
                const data = res.data
                if (data.StatusCode == 200) {
                    vm.tempData = data.Data.order
                    vm.tempDetail = data.Data.detail
                    vm.tempData.displayName = data.Data.displayName
                    vm.tempData.medicalCardNo = data.Data.medicalCardNo
                } else {
                    this.$Message.error({ title: '提示', content: data.Errors })
                }
            })
        },
        GetSaleOrderAndPrint(id) {
            GetSaleOrderAndPrint(id).then((res) => {
                const data = res.data
                if (data.StatusCode == 200) {
                    document
                        .getElementById('iframe-print')
                        .contentWindow.printData(data.Data)
                } else {
                    this.$Message.error({ title: '提示', content: data.Errors })
                }
            })
        },

        GetSystemConfig() {
            let vm = this
            GetSystemConfig().then((res) => {
                const data = res.data
                if (data.StatusCode == 200) {
                    vm.configData = data.Data
                } else {
                    Message.error({ title: '提示', content: data.Errors })
                }
            })
        }
    },
    mounted() {
        this.tempData.OrderDate = this.dayjs().format('YYYY年MM月DD日')
        this.GetSystemConfig()
        if (this.Id > 0) {
            this.GetSaleOrder()
        }
    }
}
</script>

<style></style>
